from umqtt.simple import MQTTClient
import time
from machine import Pin

def light():   
    pin2 = Pin(2, Pin.OUT)
    pin2.value(1)

def close():
    pin2 = Pin(2, Pin.OUT)
    pin2.value(0)

mqtt_client = None
count = 0
def do_connect(wifi_ssid, wifi_key):
    print(wifi_ssid,wifi_key)
    import machine, network
    wlan = network.WLAN()
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(wifi_ssid, wifi_key)
        while not wlan.isconnected():
            machine.idle()
    print('network config:', wlan.ipconfig('addr4'))
    
# 回调函数，收到服务器消息后会调用这个函数
def on_mqtt_message(topic, msg):
    """处理接收到的MQTT消息"""
    try:
        topic_str = topic.decode('utf-8')
        msg_str = msg.decode('utf-8')
        light()
        print(f"\n收到消息")
        print(f"主题: {topic_str}")
        print(f"内容: {msg_str}")
        print("------------------------")
    except Exception as e:
        print(f"消息解析错误: {e}")
        
# 5. 发送消息（核心步骤）
def send_mqtt_message(topic, message, qos=0, retain=False):
    """
    发送MQTT消息
    :param topic: 主题（字节串，如 b"test/topic"）
    :param message: 消息内容（字节串，如 b"hello" 或 "hello".encode()）
    :param qos: 服务质量等级（0/1/2，默认0）
    :param retain: 是否为保留消息（默认False）
    """
    try:
        mqtt_client.publish(topic, message, qos, retain)
        print(f"已发送消息到主题 {topic.decode()}: {message.decode()}")
    except Exception as e:
        print(f"发送消息失败: {e}")
    
def clientMqtt(MQTT_CLIENT_ID,MQTT_SERVER,MQTT_PORT,MQTT_USER,MQTT_PASSWORD):
    last_interaction = time.time()
    KEEPALIVE = 60
    TOPICS = [b"/esp32/topic/status"]
    SUBTOPICS = [b"/esp32/topic/status"]
    global mqtt_client
    mqtt_client=MQTTClient(
            MQTT_CLIENT_ID,
            MQTT_SERVER,
            MQTT_PORT,
            MQTT_USER,
            MQTT_PASSWORD,
            KEEPALIVE  # 30秒心跳间隔
        )
    mqtt_client.set_callback(on_mqtt_message)
    
    try:
        mqtt_client.connect()
        for item in TOPICS:
            mqtt_client.subscribe(item)
            #send_mqtt_message(b"test/mqttx",'test',1,False)
        #mqtt_client.subscribe(b"testtopic/test")
        send_mqtt_message(SUBTOPICS[0],'online',1,False)
        while True:
            try:
                mqtt_client.check_msg()
                if time.time() - last_interaction > KEEPALIVE / 2:
                    print('发送包')
                    mqtt_client.ping()  # 发送心跳包
                    last_interaction = time.time()  # 更新时间
                time.sleep(0.1)
            except OSError as e:
                print(f"校验信息: {e}")
        print("MQTT连接成功！",mqtt_client)
        return mqtt_client
    except OSError as e:
        print(f"连接失败: {e}")
        # 打印错误码含义
        if e.errno == 113:
            print("错误原因：网络不可达（EHOSTUNREACH）")
            return None
        elif e.errno == 111:
            print("错误原因：连接被拒绝（ECONNREFUSED）")
            return None
        elif e.errno == 104:
            print("错误原因：连接被重置（ECONNRESET）")
            return None 
    return mqtt_client
    
